﻿using System.IO;
using System.Text;
using System.Web;
using SassAndCoffee;

namespace Telerik.Web.Mvc.UI {
    internal static class Utility {
        static object _gate = 42;

        internal static string Compile(string source, string filesPath, ISimpleFileCompiler compiler) {
            var output = Path.GetFileNameWithoutExtension(source) + compiler.OutputFileExtension;

            // If the source extension is equal to output extension, do not compile
            if(output.Equals(source, System.StringComparison.InvariantCultureIgnoreCase))
                return source;

            var inFile = new FileInfo(HttpContext.Current.Server.MapPath(Path.Combine(filesPath, source)));
            var outFile = new FileInfo(HttpContext.Current.Server.MapPath(Path.Combine(filesPath, output)));

            if(!inFile.Exists)
                throw new FileNotFoundException("file not found", source);

            if(outFile.Exists && outFile.LastWriteTime > inFile.LastWriteTime)
                return output;

            using(var of = File.Create(outFile.FullName)) {
                lock(_gate) {
                    compiler.Init(HttpContext.Current.ApplicationInstance);
                    var buf = Encoding.UTF8.GetBytes(compiler.ProcessFileContent(inFile.FullName));
                    of.Write(buf, 0, buf.Length);
                }
            }

            return output;
        }
    }
}